<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>库存状况</h1>
      <div class="breadcrumb">库存状况</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>仓库名称</label>
          <input v-model="searchForm.warehouseName" type="text" placeholder="请输入仓库名称" />
        </div>
        <div class="form-item">
          <label>商品名称</label>
          <input v-model="searchForm.productName" type="text" placeholder="请输入商品名称" />
        </div>
        <div class="form-item">
          <label>规格编号</label>
          <input v-model="searchForm.specification" type="text" placeholder="请输入规格编号" />
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="searchInventory">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 库存列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th>商品名称</th>
          <th>商品编号</th>
          <th>规格编号</th>
          <th>仓库名称</th>
          <th>批次号</th>
          <th>有效期</th>
          <th>库存数量</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in inventoryList" :key="item.id">
          <td>{{ item.productName }}</td>
          <td>{{ item.productCode }}</td>
          <td>{{ item.specification }}</td>
          <td>{{ item.whName || '-' }}</td>
          <td>{{ item.batchNo || '-' }}</td>
          <td>{{ formatDate(item.expiryDate) }}</td>
          <td>{{ item.quantity }}</td>
          <td>
            <button class="btn btn-small btn-primary" @click="viewDetail(item)">详情</button>
          </td>
        </tr>
        <tr v-if="inventoryList.length === 0">
          <td colspan="8" class="text-center">暂无数据</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalItems > 0">
      <div class="pagination-info">
        共{{ totalPages }}页/{{ totalItems }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
      </div>
      <div class="pagination-jump">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="totalPages" />
        <span>页</span>
        <button class="btn btn-small" @click="jumpToPage">确定</button>
      </div>
    </div>
  </div>

  <!-- 详情弹窗 -->
  <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ detail.productName || '库存详情' }}</h3>
        <button class="modal-close" @click="showDetailModal = false">&times;</button>
      </div>
      <div class="modal-body">
        <!-- 顶部概要信息 -->
        <div class="summary-bar">
          <div class="summary-item">
            <div class="label">商品编号</div>
            <div class="value">{{ detail.productCode || '-' }}</div>
          </div>
          <div class="summary-item">
            <div class="label">规格型号</div>
            <div class="value">{{ detail.specification || '-' }}</div>
          </div>
          <div class="summary-item">
            <div class="label">单位</div>
            <div class="value">{{ detail.unit || '个' }}</div>
          </div>
          <div class="summary-item">
            <div class="label">库存总量</div>
            <div class="value strong">{{ detail.quantity ?? '-' }}</div>
          </div>
        </div>

        <!-- 选项卡 -->
        <div class="tabs">
          <div class="tabs-bar">
            <button class="tab-btn" :class="{ active: detailActive === 'stock' }" @click="detailActive = 'stock'">库存详情</button>
            <button class="tab-btn" :class="{ active: detailActive === 'in' }" @click="detailActive = 'in'">入库记录</button>
            <button class="tab-btn" :class="{ active: detailActive === 'out' }" @click="detailActive = 'out'">出库记录</button>
          </div>

          <!-- 库存详情 -->
          <div v-show="detailActive === 'stock'">
            <div class="detail-filters">
              <div class="form-item">
                <label>仓库名称</label>
                <input v-model="detailFilter.warehouseName" type="text" placeholder="请输入仓库名称" />
              </div>
              <div class="form-item">
                <label>库房类型</label>
                <select v-model="detailFilter.warehouseType">
                  <option value="">请选择</option>
                  <option value="电器仓库">电器仓库</option>
                  <option value="普通仓库">普通仓库</option>
                </select>
              </div>
            </div>

            <div class="table-container">
              <table class="data-table">
                <thead>
                <tr>
                  <th>序号</th>
                  <th>库存数量</th>
                  <th>仓库名称</th>
                  <th>仓库编号</th>
                  <th>库房类型</th>
                  <th>负责人</th>
                  <th>联系电话</th>
                  <th>库房地址</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(r, i) in stockRows" :key="i">
                  <td>{{ i + 1 }}</td>
                  <td>{{ r.quantity }}</td>
                  <td>{{ r.warehouseName || '-' }}</td>
                  <td>{{ r.warehouseCode || '-' }}</td>
                  <td>{{ r.warehouseType || '-' }}</td>
                  <td>{{ r.manager || '-' }}</td>
                  <td>{{ r.phone || '-' }}</td>
                  <td>{{ r.address || '-' }}</td>
                </tr>
                <tr v-if="!stockRows.length">
                  <td colspan="8" class="text-center">暂无数据</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 入库记录 -->
          <div v-show="detailActive === 'in'">
            <div class="table-container">
              <table class="data-table">
                <thead>
                <tr>
                  <th>操作时间</th>
                  <th>入库数量</th>
                  <th>入库原因</th>
                  <th>操作人</th>
                  <th>备注</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(r, i) in inRecords" :key="i">
                  <td>{{ formatDate(r.operateTime) }}</td>
                  <td>{{ r.quantity }}</td>
                  <td>{{ r.reason || '-' }}</td>
                  <td>{{ r.operator || '-' }}</td>
                  <td>{{ r.remark || '-' }}</td>
                </tr>
                <tr v-if="!inRecords.length">
                  <td colspan="5" class="text-center">暂无入库记录</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- 出库记录 -->
          <div v-show="detailActive === 'out'">
            <div class="table-container">
              <table class="data-table">
                <thead>
                <tr>
                  <th>操作时间</th>
                  <th>出库数量</th>
                  <th>出库原因</th>
                  <th>操作人</th>
                  <th>备注</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(r, i) in outRecords" :key="i">
                  <td>{{ formatDate(r.operateTime) }}</td>
                  <td>{{ r.quantity }}</td>
                  <td>{{ r.reason || '-' }}</td>
                  <td>{{ r.operator || '-' }}</td>
                  <td>{{ r.remark || '-' }}</td>
                </tr>
                <tr v-if="!outRecords.length">
                  <td colspan="5" class="text-center">暂无出库记录</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" @click="showDetailModal = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet } from '../../utils/api.js'

// 查询条件
const searchForm = reactive({
  warehouseName: '',
  productName: '',
  specification: ''
})

// 列表与分页
const inventoryList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalItems = ref(0)
const jumpPage = ref(1)

// 详情
const showDetailModal = ref(false)
const detail = reactive({})
const detailActive = ref('stock')
const detailFilter = reactive({ warehouseName: '', warehouseType: '' })
const stockRows = ref([])
const inRecords = ref([])
const outRecords = ref([])

// 计算属性
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 方法
const searchInventory = async () => {
  await loadInventoryData()
}

const resetSearch = async () => {
  searchForm.warehouseName = ''
  searchForm.productName = ''
  searchForm.specification = ''
  currentPage.value = 1
  await loadInventoryData()
}

const changePage = async (page) => {
  currentPage.value = page
  await loadInventoryData()
}

const jumpToPage = async () => {
  if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
    currentPage.value = jumpPage.value
    await loadInventoryData()
  }
}

const viewDetail = async (row) => {
  try {
    showDetailModal.value = true
    const data = await apiGet(`/inventory/${row.id}`)
    Object.assign(detail, data || {})
    // 填充顶栏
    // 模拟库存分布（后端若提供明细可替换以下逻辑）
    stockRows.value = [{
      quantity: row.quantity,
      warehouseName: row.whName || '一号仓库',
      warehouseCode: 'CK001',
      warehouseType: '电器仓库',
      manager: '负责人',
      phone: '13333333333',
      address: '仓库地址'
    }]

    // 拉取入/出库记录
    inRecords.value = await apiGet(`/inventory/${row.id}/in-records`)
    outRecords.value = await apiGet(`/inventory/${row.id}/out-records`)
  } catch (e) {
    console.error('获取详情失败:', e)
    Object.assign(detail, row || {})
  }
}
const formatDate = (v) => {
  if (!v) return '-'
  const d = new Date(v)
  if (isNaN(d.getTime())) return '-'
  const pad = (n) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}

const loadInventoryData = async () => {
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      size: pageSize.value,
      ...(searchForm.productName && { productName: searchForm.productName }),
      ...(searchForm.specification && { specification: searchForm.specification }),
      ...(searchForm.warehouseName && { warehouseName: searchForm.warehouseName })
    })

    const data = await apiGet(`/ware-service/inventory?${params}`)
    // data 结构：{ records, total, pages, current, size }
    const payload = data || {}
    inventoryList.value = payload.records || []
    totalItems.value = payload.total || 0
    totalPages.value = payload.pages || 1
    currentPage.value = payload.current || currentPage.value
  } catch (error) {
    console.error('加载库存数据失败:', error)
    inventoryList.value = []
    totalItems.value = 0
    totalPages.value = 1
  }
}

// 生命周期
onMounted(() => {
  loadInventoryData()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 20px;
  align-items: flex-end;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item input,
.form-item select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 150px;
}

.form-buttons {
  display: flex;
  gap: 10px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th,
.data-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.data-table tbody tr:hover {
  background: #f8f9fa;
}

.status-unpaid {
  color: #dc3545;
  font-weight: 500;
}

.status-partial {
  color: #ffc107;
  font-weight: 500;
}

.status-paid {
  color: #28a745;
  font-weight: 500;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.pagination-info {
  color: #666;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.pagination-jump {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-jump input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-danger:hover {
  background: #c82333;
}

.btn-page {
  background: white;
  border: 1px solid #ddd;
  color: #333;
  padding: 6px 12px;
}

.btn-page:hover {
  background: #f8f9fa;
}

.btn-page.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-page:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 1000px;
  max-width: 95vw;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.summary-bar {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  background: #eef1f6;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
}
.summary-item .label { color: #666; font-size: 12px; }
.summary-item .value { color: #333; font-size: 16px; }
.summary-item .value.strong { font-weight: 600; }

.tabs { margin-top: 12px; }
.tabs-bar { display: flex; gap: 8px; margin-bottom: 12px; }
.tab-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
}
.tab-btn.active { background: #4c8dff; color: #fff; border-color: #4c8dff; }

.detail-filters { display: flex; gap: 16px; margin-bottom: 12px; }

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
